package de.htwg_konstanz.ebus.framework.view;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import de.htwg_konstanz.ebus.framework.impEx.IExporter;
import de.htwg_konstanz.ebus.framework.impEx.XmlExporter;

public class ExportAction implements IAction {

	public static final String ACTION_EXPORT = "export";
	
	public boolean accepts(String actionName) {
		return actionName.equalsIgnoreCase(ACTION_EXPORT);
	}

	public String execute(HttpServletRequest request, HttpServletResponse response, ArrayList<String> errorList) {
		String searchString = (String) request.getParameter("searchParam");
		
		IExporter exporter = null;
		if ("xhtml".equals(request.getParameter("outputFormat"))) {
			exporter = new XmlExporter("resources/XHTML.xslt");
		} else {
			response.setContentType("application/octet-stream");
			response.setCharacterEncoding("iso-8859-1");
			response.setHeader("content-disposition","filename=export.xml");
			
			exporter = new XmlExporter();
		}
		
		
		if (searchString == null || searchString.equals("")) {
			exporter.performExport();
		} else {
			exporter.performExport(searchString);
		}
		
		ImpExStatusModel exportStatus = exporter.getStatusModel();
		request.getSession(true).setAttribute("xmlData", exporter.getXmlString());
		
		
		//output directly, without redirect
		OutputStream out;
		try {
			out = response.getOutputStream();
			out.write(exporter.getXmlString().getBytes());
		} catch (IOException e) {
			e.printStackTrace();
		}
	
		return "#preventRedirect";
	}

}
